package NetWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClinet {
    private Socket socket = null;
    public TcpEchoClinet(String serverIp,int serverport) throws IOException {
        //这里传入的IP和端口号的含义表示不是自己绑定，而是表示和这个ip端口号建立连接。
        socket = new Socket(serverIp,serverport);
    }

    public void start(){
        System.out.println("和服务器连接成功！");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream()){
            try(OutputStream outputStream = socket.getOutputStream()){
                while (true){
                    //要做的事情，仍然是四个步骤
                    //1.从控制台读取字符串
                    System.out.println("->");
                    String request = scanner.next();
                    //2、根据读取的字符串，构造请求，发送给服务器
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();
                    //3、从服务器读取响应，解析
                    Scanner respscanner = new Scanner(inputStream);
                    String response = respscanner.next();
                    //4、把结果显示到控制台上。
                    System.out.printf("req:%s,resp:%s\n",request,response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
         TcpEchoClinet clinet = new TcpEchoClinet("127.0.0.1",9090);
         clinet.start();
    }
}
